package com.hardware.controller.category;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hardware.common.R;
import com.hardware.entity.category.CustomerCategory;
import com.hardware.service.category.CustomerCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.hardware.utils.RedisConstants.CACHE_CATEGORY_CUSTOMER_KEY;

/**
 * 分类管理
 */
@RestController
@RequestMapping("/customerCategory")
@Slf4j
public class CustomerCategoryController {

    @Autowired
    private CustomerCategoryService customerCategoryService;

    /**
     * 新增分类
     * @param category
     * @return
     */
    @PostMapping
    @CacheEvict(value = CACHE_CATEGORY_CUSTOMER_KEY, allEntries = true)
    public R<String> save(@RequestBody CustomerCategory category){
        customerCategoryService.save(category);
        return R.success("新增分类成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize){

        return customerCategoryService.page(page,pageSize);
    }

    /**
     * 根据id删除分类
     * @param id
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = CACHE_CATEGORY_CUSTOMER_KEY, allEntries = true)
    public R<String> delete(Long id){

        customerCategoryService.remove(id);
        return R.success("分类信息删除成功");
    }

    /**
     * 根据id修改分类信息
     * @param category
     * @return
     */
    @PutMapping
    @CacheEvict(value = CACHE_CATEGORY_CUSTOMER_KEY, allEntries = true)
    public R<String> update(@RequestBody CustomerCategory category){

        customerCategoryService.updateById(category);

        return R.success("修改分类信息成功");
    }

    /**
     * 根据条件查询分类数据
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = CACHE_CATEGORY_CUSTOMER_KEY)
    public R<List<CustomerCategory>> list(){
        //条件构造器
        LambdaQueryWrapper<CustomerCategory> queryWrapper = new LambdaQueryWrapper<>();
        //添加排序条件
        queryWrapper.orderByAsc(CustomerCategory::getSort).orderByDesc(CustomerCategory::getUpdateTime);

        List<CustomerCategory> list = customerCategoryService.list(queryWrapper);
        return R.success(list);
    }
}
